﻿using FieldTools.Client.Command;
using FieldTools.Client.Entity.MyQQ;
using MessageBox = HandyControl.Controls.MessageBox;
//using FieldTools.Client.HttpServer;
using FieldTools.Client.Model.Page;
using FieldTools.Client.Model.Window;
using FieldTools.Client.Tools.HttpServer;
using FieldTools.Util;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Forms;
using FieldTools.Client.Entity.Model;
using FieldTools.Client.Business.Business;
using System.IO;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// httpServer视图模型
    /// </summary>
    public class HttpServerViewModel : NotificationObject, ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public HttpServerViewModel()
        {
            openButtonEnable = true;
            closeButtonEnable = false;
            //获取配置文件数据
            
            obj = CacheHelper.GetOrSetCache(nameof(HttpServerModel), new HttpServerModel());
            if(obj.CustomApis == null || (obj.CustomApis != null && obj.CustomApis.Count==0))
            {
                obj.CustomApis = new([ new() { Path = "gettime",
                    Parm = null,
                    RequestType = RequestType.GET,
                    IsEnable = true,
                    ScriptType = ScriptType.CShape脚本,
                    ScriptContent = "public string Excute(){return System.DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\");}",
                    Remark = "默认请求，可获取当前时间"} 
                ]);
            }
            
            //端口信息
            string jsonUrls = JsonExtention.GetAppsettingJson("urls", "appsettings.json") ?? "";
            string[] _url = jsonUrls.Split(':');
            string port = _url[2];
            obj.Port = port;
            //是否自动启动
            var setting = CacheHelper.GetOrSetCache(nameof(SettingModel), new SettingModel());
            IsAutoStart = setting.IsAutoStartHttpService;
            if (IsAutoStart) RunWebServer();
        }
        #region 实体
        public HttpServerModel obj { get; set; } = new();
        private bool IsAutoStart { get; set; } = false;

        private bool? openButtonEnable;
        /// <summary>
        /// 打开服务器按钮是可用状态
        /// </summary>
        public bool? OpenButtonEnable
        {
            get { return openButtonEnable; }
            set
            {
                openButtonEnable = value;
                this.RaisePropertyChanged(nameof(OpenButtonEnable));
            }
        }

        private bool? closeButtonEnable;
        /// <summary>
        /// 关闭服务器按钮是可用状态
        /// </summary>
        public bool? CloseButtonEnable
        {
            get { return closeButtonEnable; }
            set
            {
                closeButtonEnable = value;
                this.RaisePropertyChanged(nameof(CloseButtonEnable));
            }
        }


        #endregion

        #region 事件

        private BaseCommand openServer;
        /// <summary>
        /// 打开服务器
        /// </summary>
        public BaseCommand OpenServer
        {
            get
            {
                openServer ??= new BaseCommand(new Action<object>(o =>
                    {
                        RunWebServer();
                    }));
                return openServer;
            }
        }

        private BaseCommand closeServer;
        /// <summary>
        /// 关闭服务器
        /// </summary>
        public BaseCommand CloseServer
        {
            get
            {
                closeServer ??= new BaseCommand(new Action<object>(o =>
                    {
                        StopWebServer();
                    }));
                return closeServer;
            }
        }

        private BaseCommand addMyCustomOrder;
        /// <summary>
        /// 添加自定义回复指令
        /// </summary>
        public BaseCommand AddMyCustomOrder
        {
            get
            {
                addMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    AddCustomOrder();
                }));
                return addMyCustomOrder;
            }
        }
        private BaseCommand deleteMyCustomOrder;
        /// <summary>
        /// 删除自定义回复指令
        /// </summary>
        public BaseCommand DeleteMyCustomOrder
        {
            get
            {
                deleteMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    DeleteCustomOrder(o);
                }));
                return deleteMyCustomOrder;
            }
        }

        private BaseCommand changeMyCustomOrder;
        /// <summary>
        /// 修改自定义指令
        /// </summary>
        public BaseCommand ChangeMyCustomOrder
        {
            get
            {
                changeMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    ChangeCustomOrder(o);
                }));
                return changeMyCustomOrder;
            }
        }

        private BaseCommand exportMyCustomOrder;
        /// <summary>
        /// 导出自定义指令
        /// </summary>
        public BaseCommand ExportMyCustomOrder
        {
            get
            {
                exportMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    SaveFileDialog sfd = new()
                    {
                        Title = "保存配置文件",
                        InitialDirectory = Environment.CurrentDirectory,
                        Filter = "json文本| *.json"
                    };
                    sfd.ShowDialog();

                    string path = sfd.FileName;
                    if (path == "")
                    {
                        return;
                    }
                    try
                    {
                        CacheHelper.ExportCache(nameof(HttpServerModel), path);
                        MessageBox.Success("保存成功");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Success("保存失败:"+ex.Message);
                    }
                }));
                return exportMyCustomOrder;
            }
        }

        private BaseCommand importMyCustomOrder;
        /// <summary>
        /// 导入自定义指令
        /// </summary>
        public BaseCommand ImportMyCustomOrder
        {
            get
            {
                importMyCustomOrder ??= new BaseCommand(new Action<object>(o =>
                {
                    OpenFileDialog ofd = new()
                    {
                        Title = "打开配置文件",
                        InitialDirectory = Environment.CurrentDirectory,
                        Filter = "json文本| *.json"
                    };
                    ofd.ShowDialog();

                    string path = ofd.FileName;
                    if (path == "")
                    {
                        return;
                    }
                    try
                    {
                        CacheHelper.ImportCache(nameof(HttpServerModel), path);
                        obj = CacheHelper.GetOrSetCache<HttpServerModel>(nameof(HttpServerModel), new());
                        MessageBox.Success("导入成功");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Success("导入失败:" + ex.Message);
                    }
                }));
                return importMyCustomOrder;
            }
        }
        #endregion

        #region 功能方法
        Task? serverTask = null;
        CancellationTokenSource tokenSource = new();
        CancellationToken token = new();

        /// <summary>
        /// 开启http服务器
        /// </summary>
        private void RunWebServer()
        {
            OpenButtonEnable = false;
            //获取指定的端口以及超时时间
            //string jsonStr = JsonExtention.GetAppsettingJson("urls") ?? "";
            JsonExtention.UpdateAppsettingJson("urls", "http://*:" + obj.Port);

            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            serverTask = Task.Factory.StartNew(async () => { await MyHttpApi.RunServer(token); }, token);
            long timeOut = obj.TimeOut.IsNullOrEmpty() ? 2000 : obj.TimeOut.ToInt();//超时等待
            while (serverTask.Status != TaskStatus.Running)
            {
                Task.Delay(100);
                timeOut -= 100;
                if (timeOut < 0 || serverTask.Status == TaskStatus.Running) break;
            }
            if (serverTask.Status == TaskStatus.Running)
            {
                CloseButtonEnable = true;
                Console.WriteLine("服务打开成功");
                MessageBox.Show("服务端打开成功");
            }
            else
            {
                Console.WriteLine("http服务开启超时，请检查参数或稍后再试\r\n");
                tokenSource.Cancel();
                OpenButtonEnable = true;
                MessageBox.Show("服务端打开失败");
            }
        }

        /// <summary>
        /// 关闭http服务器
        /// </summary>
        private void StopWebServer()
        {
            if (serverTask != null && serverTask.Status == TaskStatus.Running || (serverTask != null && serverTask.Status == TaskStatus.RanToCompletion))
            {
                tokenSource.Cancel();
                if (serverTask.Status == TaskStatus.Canceled || serverTask.Status == TaskStatus.RanToCompletion)
                {
                    serverTask.Dispose();
                    OpenButtonEnable = true;
                    CloseButtonEnable = false;
                    MessageBox.Show("服务端已关闭");
                    Console.WriteLine("http服务已关闭\r\n");
                }
                else
                {
                    MessageBox.Show("服务端关闭失败");
                    Console.WriteLine("http服务关闭失败\r\n");
                }
            }

        }

        /// <summary>
        /// 添加自定义回复指令
        /// </summary>
        private void AddCustomOrder()
        {
            if (obj.CustomApis == null || obj.CustomApis.Count == 0)
            {
                obj.CustomApis = [];
            }
            obj.CustomApis?.Add(new()
            {
                Path = "testApi",
                Parm = null,
                RequestType = RequestType.GET,
                IsEnable = true,
                ScriptType = ScriptType.纯文本,
                ScriptContent = "请修改",
                Remark = ""
            }); ;
        }

        /// <summary>
        /// 删除指令表格数据
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteCustomOrder(object? obj)
        {
            try
            {
                if (obj == null)
                    return;
                if (obj is not DataGrid dataGrid) return;

                MessageBoxResult result = MessageBox.Show("是否删除当前选择项？", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var selectedItems = (dataGrid?.SelectedItems).ToJson().ToObject<List<CustomApi>>();
                    var orders = this.obj.CustomApis?.CastToList<CustomApi>();
                    selectedItems?.ForEach(o =>
                    {
                        var index = orders?.FindIndex(x => x.Id == o.Id);
                        if (index != null && index != -1)
                        {
                            this.obj.CustomApis?.RemoveAt((int)index);
                        }
                    });
                    MessageBox.Show("数据删除成功，请注意保存");
                }
                else if (result == MessageBoxResult.No)
                {
                    //不删除
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据删除失败：" + ex);
            }

        }
        /// <summary>
        /// 修改自定义指令
        /// </summary>
        /// <param name="o"></param>
        private void ChangeCustomOrder(object? o)
        {
            if (o == null)
                return;
            if (o is not DataGrid dataGrid) return;
            var items = dataGrid.ItemsSource.CastToList<CustomApi>();
            if (items != null)
            {
                obj.CustomApis = new(items);
            }
        }

        #endregion
    }
}
